<template>
  <div class="editDetectTypeDiv">
    <Button @click="cancel"
            type="primary">返 回</Button>
    <Form :model="dataObj"
          label-position="left"
          :label-width="80">

      <FormItem label="图标:">
        <img v-if="dataObj.imageUrl"
             :src="dataObj.imageUrl"
             width="100px"
             height="100px"
             style="border-radius: 5%" />
        <Upload :action="fileUploadAction"
                :max-size='fileMaxSize'
                :on-exceeded-size="showError"
                :on-success="uploadSuccess">
          <Button icon="ios-cloud-upload-outline">头像上传</Button>
        </Upload>
      </FormItem>

      <FormItem label="名称:">
        <Input v-model="dataObj.name"
               type="text"
               class="w-200"
               placeholder="请输入名称" />
      </FormItem>

      <FormItem label="序号:">
        <Input v-model="dataObj.sortNum"
               type="text"
               class="w-200"
               placeholder="请输入序号" />
      </FormItem>

      <FormItem label="标签:">
        <Input v-model="dataObj.labels"
               type="text"
               class="w-200"
               placeholder="请输入标签" />
      </FormItem>

      <FormItem label="类别:">
        <Select v-model="dataObj.type"
                class="w-200"
                placeholder="请选择类别"
                @on-change="changeType">
          <Option v-for="item in typeList"
                  :value="item.id"
                  :key="item.id">{{ item.name }}</Option>
        </Select>
      </FormItem>
      <FormItem label="对应子集:"
                v-if="isShow">
        <Select v-model="dataObj.childType"
                class="w-200"
                placeholder="请选择对应子集">
          <Option v-for="item in childTypeList"
                  :value="item.id"
                  :label="item.name"
                  :key="item.id">{{ item.name }}</Option>
        </Select>
      </FormItem>
      <FormItem label="子类别图标:"
                v-if="isShow">
        <img v-if="dataObj.childImageUrl"
             :src="dataObj.childImageUrl"
             width="100px"
             height="100px"
             style="border-radius: 5%" />
        <Upload :action="fileUploadAction2"
                :max-size='fileMaxSize2'
                :on-exceeded-size="showError2"
                :on-success="uploadSuccess2">
          <Button icon="ios-cloud-upload-outline">子类别图标上传</Button>
        </Upload>
      </FormItem>
    </Form>
    <el-button type="primary"
               @click="handleEdit">新 增</el-button>
    <Table border
           :columns="titles"
           :data="dataObj.detectTypeItemDtoList"
           class="mt-20">
      <template slot-scope="{row, index}"
                slot="action">
        <span @click="handleOption(row, index , 'edit')">编辑</span>
        <span @click="handleOption(row, index, 'del')">删除</span>
      </template>
    </Table>

    <Modal v-model="editPage"
           title="检测项目配置"
           width="500"
           footer-hide
           @on-ok="saveItem"
           @on-cancel="editPage = false">
      <el-form :model="editItem"
               label-position="right"
               label-width="100px"
               ref="formValidateRef"
               :rules="ruleValidateRules">
        <el-form-item label="检测项目:">
          <el-select v-model="editItem.deviceId"
                     class="w-200"
                     filterable
                     :disabled="isEdit"
                     @change="changeDevice"
                     placeholder="请选择检测项目">
            <el-option v-for="item in tempDeviceList"
                       :label="item.name"
                       :value="item.id"
                       :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称:"
                      prop="name">
          <el-input v-model="editItem.name"
                    type="text"
                    :disabled="isEdit"
                    class="w-200"
                    placeholder="请选择检测项目获取名字" />
        </el-form-item>
        <el-form-item label="序号:"
                      prop="sortNum">
          <el-input v-model="editItem.sortNum"
                    type="text"
                    class="w-200"
                    placeholder="请输入序号" />
        </el-form-item>
      </el-form>
      <p align="center">
        <el-button plain
                   @click="editPage = false">取 消</el-button>
        <el-button type="primary"
                   v-prevent-re-click
                   @click="saveItem">确 定</el-button>
      </p>
    </Modal>
    <p class="mt-20"
       align="center">
      <el-button @click="cancel"
                 plain>返 回</el-button>
      <el-button type="success"
                 v-prevent-re-click
                 @click="saveData">保 存</el-button>
    </p>
    <el-dialog title="图标"
               center
               :visible.sync="imageModal"
               width="30%">
      <img :src="imageUrl"
           style="width:100%;height:100%">
      <span slot="footer">
        <el-button type="primary"
                   @click="imageModal = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "editDetectType",
    data () {
      return {
        imageModal: false,
        imageUrl: null,
        editPage: false,
        fileUploadAction: null,
        fileUploadAction2: null,
        fileMaxSize: 1024 * 50,
        fileMaxSize2: 1024 * 50,
        typeList: [
          { id: 1, name: "按检查类型检测" },
          { id: 2, name: "按病症类别检测" },
          { id: 3, name: "毒品检测" },
          { id: 4, name: "校园快检" },
          { id: 5, name: "独家/特色" }
        ],
        childTypeList: [
          { id: 1, name: "【幼儿园-小学】快检" },
          { id: 2, name: "【初中-高中】快检" },
          { id: 3, name: "【职业学校-大学】快检" }
        ],
        titles: [
          {
            title: '图标',
            key: 'imageUrl',
            width: 95,
            render: (h, params) => {
              return h('div', [
                h('img', {
                  attrs: {
                    src: params.row.imageUrl
                  },
                  style: {
                    width: '60px',
                    height: '60px',
                    'border-radius': '50%'
                  },
                  on: {
                    click: (event) => {
                      this.showBigImage(params.row.imageUrl);
                    }
                  }
                }),
              ]);
            }
          },
          {
            title: '名称 ',
            key: 'name',
            render: (h, params) => {
              return h('div', [
                h("div", [h('span', params.row.name)]),
              ]);
            }
          },
          {
            title: '项目名称 ',
            key: 'deviceName',
            render: (h, params) => {
              return h('div', [
                h("div", [h('span', params.row.deviceName)]),
              ]);
            }
          },

          {
            title: '排序号 ',
            key: 'sortNum',
            width: 100,
          },
          {
            title: '操作',
            slot: 'action',
            align: 'center',
            width: 120
          }
        ],
        deviceList: [],
        tempDeviceList: [],
        dataObj: {
          id: null,
          imageUrl: '',
          name: '',
          sortNum: '',
          labels: '',
          type: 2,
          childType: null, // 子类别
          childImageUrl: '', // 子类别图标
          detectTypeItemDtoList: [],
          detectTypeItemDto: {}
        },
        // 检测项目配置参数
        editItem: {
          id: null,
          name: '',
          detectTypeId: null,
          imageUrl: '',
          deviceName: '',
          deviceId: '',
          sortNum: ''
        },
        isShow: false,
        isEdit: false,
        currId: '',
        // 校验检测项目配置
        ruleValidateRules: {
          deviceId: [
            { required: false, message: '请选择检测项目', trigger: 'change' }
          ],
          name: [
            { required: true, message: '请选择检测项目获取名字', trigger: 'blur' }
          ],
          sortNum: [
            { required: true, message: '请输入序号', trigger: 'blur' }
          ],
        }
      }
    },
    mounted () {
      if (this.$route.query.id) {
        this._getDataById();
      } else {
        this._getDeviceList();
      }
    },
    created () {
      this.fileUploadAction = this.api.file.upload;
      this.fileUploadAction2 = this.api.file.upload;
    },
    methods: {
      showBigImage (url) {
        this.imageUrl = url;
        this.imageModal = true;
      },
      // 查询详情
      _getDataById () {
        this.post(this.api.detectType.getDetectTypeDetail, {
          id: this.$route.query.id == undefined ? this.currId : this.$route.query.id
        }).then((res) => {
          if (res.data.code === '200') {
            this.dataObj = res.data.object;
            if (this.dataObj.childImageUrl || this.dataObj.childType) {
              this.isShow = true
            }
            this.dataObj.type = Number(res.data.object.type)
            this.dataObj.childType = Number(res.data.object.childType)
            this._getDeviceList();
          }
        });
      },
      _getDeviceList () {
        this.ajax({
          type: this.api.deviceList.type,
          url: this.api.deviceList.url,
          data: {
            pageSize: 1000,
            pageStart: 0
          },
          success: (data) => {
            this.deviceList = data.object;
            this.initTempDeviceList();
          },
          error: (data) => {
            this.$Message.error(data.message);
          }
        });
      },
      initTempDeviceList () {
        this.tempDeviceList = [];
        let itemList = this.dataObj.detectTypeItemDtoList;
        for (let i = 0; i < this.deviceList.length; i++) {
          let device = this.deviceList[i];
          let isHave = false;
          if (itemList) {
            for (let j = 0; j < itemList.length; j++) {
              let item = itemList[j];
              if (item.deviceId === device.id) {
                isHave = true;
                break;
              }
            }
          }
          if (!isHave) {
            this.tempDeviceList.push(device);
          }
        }
      },
      uploadSuccess (obj) {
        if (obj.code === '200') {
          this.$message.success("上传成功");
          this.dataObj.imageUrl = obj.object[0];
        } else {
          this.$message.error("上传失败");
        }
      },
      showError (file, fileList) {
        this.$Notice.warning({
          title: '文件大小超限',
          desc: '文件  ' + file.name + ' 太大，上传文件大小不能超过50M.'
        });
      },
      // 子类别图标上传成功
      uploadSuccess2 (obj) {
        if (obj.code === '200') {
          this.$message.success("上传成功");
          this.dataObj.childImageUrl = obj.object[0];
        } else {
          this.$message.error("上传失败");
        }
      },
      // 子类别图标上传限制
      showError2 (file, fileList) {
        this.$Notice.warning({
          title: '文件大小超限',
          desc: '文件  ' + file.name + ' 太大，上传文件大小不能超过50M.'
        });
      },
      // 新增
      handleEdit () {
        this.editPage = true;
        this.isEdit = false;
        this.editItem = {
          id: '',
          name: '',
          imageUrl: '',
          deviceName: '',
          deviceId: '',
          sortNum: ''
        }
        this.initTempDeviceList();
      },
      // 删除、编辑
      async handleOption (row, index, option) {
        switch (option) {
          case 'del':
            const { data: res } = await this.post(this.api.detectType.deleteDetectTypeItem, {
              id: this.dataObj.id,
              detectTypeItemDto: row
            })
            if (res.code === '200') {
              this.$message.success('删除成功!')
              this._getDataById()
            }
            break;
          case 'edit':
            this.editPage = true;
            this.isEdit = true;
            this.editItem = Object.assign({}, row);
            this.editItem.deviceId = row.deviceId;
            this.tempDeviceList = [{
              id: row.deviceId,
              name: row.deviceName
            }];
            break;
        }
      },
      // 保存
      saveData () {
        if (this.editPage) {
          this.dataObj.detectTypeItemDto = this.editItem;
          this.$refs.formValidateRef.validate((valid) => {
            if (valid) {
              this.post(this.api.detectType.updateDetectType, this.dataObj).then((res) => {
                if (res.data.code === '200') {
                  // this.$router.push({ name: 'detectTypeList' })
                  this.$message.success('保存成功!')
                  this.currId = res.data.object.id
                  this._getDataById()
                  this.editPage = false;
                }
              });
            }
          })
        } else {
          this.dataObj.detectTypeItemDto = this.dataObj.detectTypeItemDtoList[0]
          this.post(this.api.detectType.updateDetectType, this.dataObj).then((res) => {
            if (res.data.code === '200') {
              // this.$router.push({ name: 'detectTypeList' })
              this.$message.success('保存成功!')
              this.currId = res.data.object.id
              this._getDataById()
              this.editPage = false;
            }
          });
        }


      },
      changeDevice (deviceId) {
        console.log(deviceId);
        console.log(this.deviceList);
        if (deviceId) {
          for (let i = 0; i < this.deviceList.length; i++) {
            let device = this.deviceList[i];
            if (device.id === deviceId) {
              this.editItem.name = device.name;
              this.editItem.deviceName = device.name;
              this.editItem.imageUrl = device.imageUrl;
              break;
            }
          }
        }
      },
      saveItem () {
        this.saveData()
        // this.dataObj.detectTypeItemDtoList.unshift(this.editItem);
        // this.editPage = false;
      },

      cancel () {
        this.$router.push({ name: 'detectTypeList' });
      },
      // 类别
      changeType (val) {
        if (val === 4) {
          this.isShow = true;
        } else {
          this.isShow = false;
        }

      }
    }
  }
</script>

<style scoped>
  .editDetectTypeDiv {
    padding: 20px 50px;
  }
</style>
